package com.ssss.danli;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * 为啥建议枚举单例
 * 1.避免反射攻击
 */
public enum DesignEnum {

    INSTANCE;


    public DesignEnum getInstance(){
        return INSTANCE;
    }

    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        DesignEnum instance = DesignEnum.INSTANCE;
        DesignEnum instance1 = DesignEnum.INSTANCE;
        System.out.println("正常情况下，实例化两个实例是否相同："+(instance == instance1));

        Constructor<DesignEnum> constructor = null;
        constructor = DesignEnum.class.getDeclaredConstructor();
        constructor.setAccessible(true);

        DesignEnum instance2 = null;
        instance2 = constructor.newInstance();
        System.out.println("instance:"+instance +"/n instance1:"+instance1+"/n instance2:"+instance2);
        System.out.println("通过反射攻击单例模式情况下，实例化两个实例是否相同："+(instance == instance2));
    }
}
